package com.atguigu.chapter11;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/7/24 8:57
 */
public class Flink01_Table_BaseUse {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
    
        DataStreamSource<WaterSensor> stream = env.fromElements(
            new WaterSensor("sensor_1", 1L, 10),
            new WaterSensor("sensor_1", 2L, 20),
            new WaterSensor("sensor_2", 3L, 30),
            new WaterSensor("sensor_1", 4L, 40),
            new WaterSensor("sensor_1", 5L, 50)
        );
    
        // 1. 创建 table的执行环境
        StreamTableEnvironment tenv = StreamTableEnvironment.create(env);
        
        // 2. 把流转成一个动态表
        Table table = tenv.fromDataStream(stream);
        
//        table.printSchema();  // 打印schema
        // 3. 可以在表上执行连续查询
        // select * from t where id='sensor_1'
        /*Table t1 = table
            .where("id='sensor_1'")
            .select("id,ts,vc");
        */
        /*Table t1 = table
            .where(Expressions.$("id").isEqual("sensor_1"))
            .select(Expressions.$("id"), Expressions.$("ts"), Expressions.$("vc"));*/
    
        /*Table t1 = table
            .where($("id").isEqual("sensor_1"))
            .select($("id"), $("ts"), $("vc"));*/
    
        Table t1 = table
            .where($("id").isEqual("sensor_1"))
            .select($("id").as("my_id"), $("ts").as("my_ts"), $("vc"));
    
        // 4. 把动态表转成流输出
       // DataStream<WaterSensor> result = tenv.toAppendStream(t1, WaterSensor.class);//AppendStream : 动态表的数据只有新增没有更新和删除的时候使用te
        DataStream<Row> result = tenv.toAppendStream(t1, Row.class);
        result
            .map(row -> {
                return row.getField("my_id");
            })
            .print();
    
        env.execute();
    
    }
}
